package day01;

import java.util.Iterator;

/**
 * @author Jetwang
 * @version 1.0
 * @since 2023/3/18 16:36
 */

@SuppressWarnings("all")
public class PriorityQueue02<E extends Priority> implements Queue<E>, Iterable<E> {
    Priority[] array;
    int size;

    public PriorityQueue02(int capacity) {
        array = new Priority[capacity];
    }

    @Override
    public boolean offer(E e) {
        if (isFull()) {
            return false;
        }
        insert(e);
        size++;
        return true;
    }

    public void insert(E e) {
        int i = size - 1;
        /*while(i >= 0 && array[i].priority() > e.priority()) {
            array[i + 1] = array[i];
            i--;
        }*/
        int j = i;
        for (;j >= 0 && array[j].priority() > e.priority(); j--) {
            array[j + 1] = array[j];
        }
        array[j+1] = e;
    }



    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        E e = (E) array[size-1];
        array[--size] = null; // help GC
        return e;
    }


    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }
        return (E) array[size-1];
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return array.length == size;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int i = 0;
            @Override
            public boolean hasNext() {
                return i < size;
            }

            @Override
            public E next() {
                E val = (E) array[i];
                i++;
                return val;
            }
        };
    }
}
